const http = require('http')
const fs = require('fs')

http.createServer(function (request, response) {
  console.log('接收到请求')
  // console.log('request come', request.url)

  // if (request.url === '/') {
  //   const html = fs.readFileSync('user.html')
  //   response.writeHead(200, {
  //     'Content-Type': 'text/html'
  //   })
  //   response.end(html)
  // }

  if (request.url === '/api/user/getUser') {
    fs.readFile('user.json', 'utf8', function(err, data) {
      response.end(data)
    })
  }

  if (request.url === '/api/user/addUser' && request.method === 'POST') {
    let body  = ''
    request.on('data', function (chunk) {
      body += chunk
    })
    request.on('end', function () {
      body = JSON.parse(body)
      fs.readFile('user.json', 'utf8', function(err, data) {
        data = JSON.parse(data)
        let userId = guid()
        body.id = userId
        data[userId] = body
        let str = JSON.stringify(data)
        fs.writeFile('user.json', str, function(err){
          if(err){
              console.error(err);
          }
          console.log("----------添加成功------------");
        })
        response.writeHead(200, {
          'Content-Type': 'text/plain; charset=UTF-8'
        })
        let res = {
          code: 1,
          info: '添加成功'
        }
        response.end(JSON.stringify(res))
      })
    })
  }

  if (request.method === 'PUT') {
    let parseData = urlParse(request.url)
    if (parseData.url === '/api/user/editUser') {
      let body = ''
      request.on('data', function (chunk) {
        body += chunk
      })
      request.on('end', function () {
        body = JSON.parse(body)
        fs.readFile('user.json', 'utf8', function(err, data) {
          data = JSON.parse(data)
          data[parseData.id] = body
          let str = JSON.stringify(data)
          fs.writeFile('user.json', str, function(err){
            if(err){
                console.error(err);
            }
            console.log("----------修改成功------------");
          })
          response.writeHead(200, {
            'Content-Type': 'text/plain; charset=UTF-8'
          })
          let res = {
            code: 1,
            info: '修改成功'
          }
          response.end(JSON.stringify(res))
        })
      })
    }
  }

  if (request.method === 'DELETE') {
    let parseData = urlParse(request.url)
    if (parseData.url === '/api/user/delUser') {
      fs.readFile('user.json', 'utf8', function(err, data) {
        data = JSON.parse(data)
        delete data[parseData.id]
        let str = JSON.stringify(data)
        fs.writeFile('user.json', str, function(err){
          if(err){
              console.error(err);
          }
          console.log("----------删除成功------------");
        })
        response.writeHead(200, {
          'Content-Type': 'text/plain; charset=UTF-8'
        })
        let res = {
          code: 1,
          info: '删除成功'
        }
        response.end(JSON.stringify(res))
      })
    }
  }

  if (request.url === '/api/user/testUser' && request.method === 'POST') {
    console.log('请求成功 /api/user/testUser')
    let body  = ''
    request.on('data', function (chunk) {
      body += chunk
    })
    request.on('end', function () {
      console.log('-----', body)
      body = JSON.parse(body)
      fs.readFile('user.json', 'utf8', function(err, data) {
        data = JSON.parse(data)
        let userInfo = ''
        for (let item in data) {
          if (data[item].name === body.name && data[item].password === body.password) {
            userInfo = data[item]
          }
        }
        response.writeHead(200, {
          'Content-Type': 'application/json'
        })
        let res
        if (userInfo.name) {
          res = {
            code: 1,
            info: userInfo
          }
        } else {
          res = {
            code: 0,
            info: '暂无该用户'
          }
        }
        console.log('发送成功')
        response.end(JSON.stringify(res))
      })
    })
  }
}).listen(8888)

function guid() {
  return 'xxxxxxxx'.replace(/[xy]/g, c => {
    var r = Math.random() * 16 | 0
    var v
    v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

function urlParse(data) {
  return {
    url: data.slice(0, -9),
    id: data.slice(-8)
  }
}
console.log('server listening on 8888')